package com.example.yrdev.ordering_system.Utils;

import com.example.yrdev.ordering_system.Model.Good;
import com.example.yrdev.ordering_system.Model.PurchaseReport;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by luke on 11/3/16.
 */

public class MIReaderUtils {

    // 16进制字符转String
    static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    public static String getStringAtRange(String string,int startIndex,int endIndex){
        ArrayList<String>arrayList=new ArrayList<>();
        for (int i=0;i<string.length();i=i+2){
            String temp =string.substring(i,i+2);
            arrayList.add(temp);

        }

        String temp="";
        for (int i=startIndex;i<=endIndex;i++){
            temp=temp+arrayList.get(i);

        }
        return temp;


    }


    private static byte toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }

    public static String convertToPurchaseReceipt(String date,String ticketId,String cardId,String totalPrice,ArrayList<PurchaseReport>purchaseReports){//消费发票

        //String result="";
        StringBuilder result=new StringBuilder();

        result.append("\n"+"日期 : "+date);
        result.append("\n"+"票号 : "+ticketId);

        if (cardId.length()>0 && cardId!=null)
            result.append("\n"+"卡号 : "+ticketId);

        result.append("\n"+"===============================");


        String titles="  项目    数量   单价   小计  ";

        String space="";

        GlobalFunction.printTextByTag(titles.indexOf("项")+"");
        for (PurchaseReport report:purchaseReports){
            for (int i=0;i<titles.length();i++){
                space=space+" ";
            }
            StringBuilder itemContent=new StringBuilder(space);

            boolean seperateName=false;
            int nameIndex=(titles.indexOf("项")-(report.getCommodityName().length())/2);
            int amountIndex=titles.indexOf("数");
            if (nameIndex<0)
                nameIndex=0;

           if (nameIndex+report.getCommodityName().length()>amountIndex){
               seperateName=true;
               String temp=report.getCommodityName().substring(nameIndex,amountIndex-2);

              itemContent.replace(nameIndex,amountIndex-2,temp);

           }else {
               itemContent.replace(nameIndex,report.getCommodityName().length(),report.getCommodityName());

           }


            String volume=String.valueOf(report.getVolume());

            itemContent.replace(amountIndex,titles.indexOf("量"),volume);


            int priceIndex=titles.indexOf("单");
            itemContent.replace(priceIndex,titles.indexOf("价"),report.getSaleCost());

            int totPriceIndex=titles.indexOf("小")+(report.getCost().length()/2);
            itemContent.replace(totPriceIndex,titles.indexOf("计")+2,report.getCost());
            String finResult=itemContent.toString();

            if (seperateName){
                String temp=report.getCommodityName().substring(amountIndex-2,report.getCommodityName().length());
                temp="\n"+temp;

            finResult=finResult+temp;


               // GlobalFunction.printTextByTag(temp);
            }
            titles=titles+"\n"+finResult;



        }

        result.append("\n"+titles).toString();
        result.append("\n"+"===============================");
        result.append("\n"+"合计 : "+totalPrice);

        GlobalFunction.printTextByTag(result.toString());

        return result.toString();

    }

    static class MIReaderObj{
        Integer sector;
        ArrayList block;
         MIReaderObj(){
            block=new ArrayList();

        }
        void setSector(Integer sector) {
            this.sector = sector;
        }

        Integer getSector() {
            return sector;
        }

       ArrayList getBlock() {
            return block;
        }
    }

   public static String convertToHexString(int x){

        System.out.println(x + "的十六进制结果是：" + Integer.toHexString(x));


        String hexString= Integer.toHexString(x);
        if (hexString.length()==1){
            hexString="0"+hexString;

        }
        return hexString;

    }
  public   static  String convertToDecimal1(String hex){
        String value="";

        try {

            int i=0;
            ArrayList<String>arrayList=new ArrayList<>();

            //  int temp=0;
            while (i<hex.length()){

                String str=hex.substring(i, i + 2);
                // GlobalFunction.printText("tag","a:"+str);
                arrayList.add(0,str);

                i=i+2;

            }
            String temp="";
            for (int j=arrayList.size()-1;j>=0;j--){

                temp=temp+arrayList.get(j);
            }

            value=String.valueOf(Integer.parseInt(temp, 16 ));

        }
        catch (Exception e){

        }
        //   GlobalFunction.printText("tag",value);
        return value;


    }


    static  String convertHexPosition(String hexStr){//前低后高
        String value="";
        ArrayList<String>arrayList=new ArrayList<>();

        try {

            int i=0;
            while (i<hexStr.length()){
                String subStr=hexStr.substring(i, i + 2);
                arrayList.add(subStr);


                i=i+2;

            }
            for (int j=arrayList.size()-1;j>=0;j--){
                String string=arrayList.get(j);
                value=value+string;
            }


        }catch (Exception e){

            e.printStackTrace();

        }
        return value;

    }
    public   static String reformatTicketContent(String ticketID,ArrayList<Good> goodsArrayList){

        String currentDateTime=GlobalFunction.getCurrentDateTime();
        String header="           发票         "+"\n-----------------------------"+"\n日期 : "+currentDateTime+"\n单号 : "+ticketID+"\n-----------------------------";




        String category="编号   商品    数量   总价";

        int totalPrice=0;
        for (Good goods:goodsArrayList){

            totalPrice=totalPrice+Integer.valueOf(goods.getTotalPrice());

            String itemNo=goods.getId();
            String itemName=goods.getName();
            String itemAmount= String.valueOf(goods.getPurchaseCount());
            String itemTotalPrice=String.valueOf(goods.getTotalPrice());

            StringBuilder space=new StringBuilder("                       ");

            GlobalFunction.printTextByTag("length"+String.valueOf(category.length())+"-"+String.valueOf(space.length()));

            int itemNoIndex=(category.indexOf("编")+category.lastIndexOf("号")+2)/2-itemName.length()/2;
            space.replace(itemNoIndex,itemNoIndex+itemNo.length(),itemNo);

            int itemNameIndex=(category.indexOf("商")+category.lastIndexOf("品")+2)/2-(itemName.length()-2)/2;
            space.replace(itemNameIndex,itemNameIndex+itemName.length(),itemName);

           int itemAmountIndex=(category.indexOf("数")+category.lastIndexOf("量")+2)/2-itemAmount.length()/2;
            space.replace(itemAmountIndex,itemAmountIndex+itemAmount.length(),itemAmount);


            GlobalFunction.printTextByTag("index:"+String.valueOf(category.indexOf("总"))+":"+String.valueOf(category.lastIndexOf("价")));

            int itemPriceIndex=(category.indexOf("总")+category.lastIndexOf("价")+3)/2-itemAmount.length()/2;

            space.replace(itemPriceIndex,itemPriceIndex+itemTotalPrice.length(),itemTotalPrice);


            category=category+"\n"+space;


        }



    String totalPriceStr="-----------------------------"+"\n合计 : "+String.valueOf(totalPrice)+"元";

    String res=header+"\n"+category+"\n"+totalPriceStr;

        GlobalFunction.printTextByTag(res);
        return res;



    }
    static  String convertFromChinese(String text) throws IOException {

        String str="";

        try {

            byte[] buf = new byte[text.length()/2];
            int i=0;

            int temp=0;

            while (i<text.length()){
                Integer integer=Integer.parseInt(text.substring(i, i + 2), 16);
                //   GlobalFunction.printText("tag",String.valueOf(integer));
                buf[temp]=(byte)Integer.parseInt( text.substring(i,i+2), 16 );
                temp++;

                i=i+2;

            }

            str =new String(buf,"GBK");

        }catch (Exception e){

        }

        return str;

    }

    public static String replaceStringAtRange(String string,int startIndex,Integer endIndex,String newVal){
        ArrayList<String>arrayList=new ArrayList<>();
        for (int i=0;i<string.length();i=i+2){
            String temp =string.substring(i,i+2);
            arrayList.add(temp);

        }
        GlobalFunction.printTextByTag("newVal："+newVal);
        ArrayList <String> tempArr=new ArrayList<>();
        for (int i=0;i<newVal.length();i=i+2){
            String temp =newVal.substring(i,i+2);
            tempArr.add(temp);
        }

        int index=0;

        for (int i=startIndex;i<=endIndex;i++){




            arrayList.set(i,tempArr.get(index));
            ++index;

        }
        //arrayList.set(index,newVal);

        StringBuilder stringBuilder=new StringBuilder();
        for (String str:arrayList
                ) {
            stringBuilder.append(str);

        }
        return stringBuilder.toString();


    }

    static  String convertToDecimal(String hex){
        String value="";

        try {

            int i=0;
            ArrayList<String>arrayList=new ArrayList<>();

            //  int temp=0;
            while (i<hex.length()){

                String str=hex.substring(i, i + 2);
                // GlobalFunction.printText("tag","a:"+str);
                arrayList.add(str);


                i=i+2;

            }
            String temp="";
            for (int j=arrayList.size()-1;j>=0;j--){

                temp=temp+arrayList.get(j);
            }

            value=String.valueOf(Integer.parseInt(temp, 16 ));

        }
        catch (Exception e){

        }
        //   GlobalFunction.printText("tag",value);
        return value;


    }

    // 字符序列转换为16进制字符串
   static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
            System.out.println(buffer);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }

}
